﻿using System.Collections;
using Newtonsoft.Json;
using LitJson;
using UnityEngine;
using Newtonsoft.Json.Linq;
using System;

namespace ZSW.Framework.Utils
{
    public static class ZSWFUtil_Json
    {

        /// <summary>
        /// 字符串转类(目前仅支持Json格式)
        /// </summary>
        public static bool ToClass<T>(this string str, out T result)
        {
            result = JsonConvert.DeserializeObject<T>(str);
            return true;
        }

        public static T GetValueFromJson<T>(string json, string key, T defaultValue = default(T))
        {
            try
            {
                // Parse the JSON string into a JObject for easy querying
                JObject jsonObject = JObject.Parse(json);

                // Retrieve the value associated with the specified key
                JToken valueToken = jsonObject.SelectToken(key);

                // If the key exists and has a non-null value, attempt to deserialize it to the specified type
                if (valueToken != null && valueToken.Type != JTokenType.Null)
                {
                    return valueToken.ToObject<T>();
                }
            }
            catch (JsonReaderException)
            {
                ZSWFUtil_Debug.LogError(typeof(ZSWFUtil_Json).ToString(), $"JsonReaderException.Json:{json} Key:{key}");
            }

            // Return the default value if the key is not found, the JSON is invalid, or the value cannot be deserialized
            return defaultValue;
        }


        public static string GetValueFromJson(string json, string key)
        {
            try
            {
                // Parse the JSON string into a JObject for easy querying
                JObject jsonObject = JObject.Parse(json);

                // Retrieve the value associated with the specified key
                JToken valueToken = jsonObject.SelectToken(key);

                // If the key exists and has a non-null value, return the value as a string
                if (valueToken != null && valueToken.Type != JTokenType.Null)
                {
                    return valueToken.ToString();
                }
            }
            catch (JsonReaderException)
            {
                // Handle any JSON parsing errors by returning an empty string
                // This may occur if the input JSON is malformed
            }

            // Return an empty string if the key is not found or there was an error parsing the JSON
            return string.Empty;
        }


        /// <summary>
        /// object转Json字符串
        /// </summary>
        public static string ToJson(this object obj) => JsonConvert.SerializeObject(obj);

        /// <summary>
        /// Hashtable转Json格式
        /// </summary>
        public static string ToJson(Hashtable hashtable)
        {
            string jsonString = JsonConvert.SerializeObject(hashtable, Formatting.Indented);
            return jsonString;
        }

        /// <summary>
        /// Json字符串转Hashtable
        /// </summary>
        public static Hashtable FromJsonToHashtable(string jsonStr)
        {
            JsonData jsonData = JsonMapper.ToObject(jsonStr);
            Hashtable table = jsonDataToHashtable(jsonData);
            return table;
        }

        /// <summary>
        /// 从Json文件读取Hashtable
        /// </summary>
        /// <param name="jsonFile"></param>
        /// <returns></returns>
        public static Hashtable LoadHashtableFromJsonFile(string jsonFile)
        {
            string jsonStr = ZSWFUtil_File.ReadTextFromFile(jsonFile);
            return FromJsonToHashtable(jsonStr);
        }

        /// <summary>
        /// 从JSON文件读取类
        /// </summary>
        /// <param name="jsonFile"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T LoadFromJson<T>(string jsonFile)
        {
            string jsonStr = ZSWFUtil_File.ReadTextFromFile(jsonFile);
            return LoadFromJsonStr<T>(jsonStr);
        }

        /// <summary>
        /// 从JSON字符串读取类
        /// </summary>
        /// <param name="jsonStr"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T LoadFromJsonStr<T>(string jsonStr)
        {
            T json = JsonUtility.FromJson<T>(jsonStr);
            return json;
        }

        /// <summary>
        /// jsonData 转 Hashtable
        /// </summary>
        private static Hashtable jsonDataToHashtable(JsonData json)
        {
            Hashtable table = new Hashtable();
            foreach (var key in json.Keys)
            {
                // Debug.Log($"{key} - {json[key].GetJsonType()}");
                if (json[key].GetJsonType() == JsonType.Object)
                {
                    table[key] = jsonDataToHashtable(json[key]);
                }
                else if (json[key].GetJsonType() == JsonType.Array)
                {
                    if (json[key][0].GetJsonType() != JsonType.Object)
                    {
                        table[key] = json[key].ToJson();
                    }
                    else
                    {
                        Hashtable[] subTable = new Hashtable[json[key].Count];
                        for (int i = 0; i < json[key].Count; i++)
                        {
                            Hashtable t = jsonDataToHashtable(json[key][i]);
                            subTable[i] = t;
                        }

                        table[key] = subTable;
                    }
                }
                else
                {
                    table[key] = json[key].ToString();
                }
            }

            return table;
        }
    }
}